package com.ruoyi.common.utils.printer;

import com.sini.xls.com.spire.xls.CellRange;
import com.sini.xls.com.spire.xls.FileFormat;
import com.sini.xls.com.spire.xls.Workbook;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import javax.print.PrintService;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.File;

public class PrintDemo {

    static Log log = LogFactory.getLog(PrintDemo.class);

    public static void main(String[] args) {

        printPdf("D:/test.xlsx", "D:/1_P1.pdf", "HP Laser MFP 131 133 135-138");

    }

    public static void printPdf(String excelName, String fileName, String printerName) {
        if (printerName.contains("HP")) {
            excelToPdf(excelName, fileName);
        } else {
            excelToPdf2(excelName, fileName);
        }

        try {
            //打印的pdf文件
            File file = new File(fileName);

            PDDocument document = PDDocument.load(file);
            PrinterJob job = findPrintService(printerName);
            configPageStyle(document, job);

            // 设置打印页范围
            PageFormat pageFormat = job.defaultPage();
            pageFormat.setOrientation(PageFormat.PORTRAIT);
            job.setPrintable(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat);

            // 开始打印当前页
            job.print();
            // 打印完成后关闭PDDocument对象
            document.close();
        } catch (Exception e) {
            log.info("异常{}" + e.getMessage());
        }
    }

    public static void excelToPdf(String excelName, String pdfName) {
        //加载Excel文档
        Workbook wb = new Workbook();
        wb.loadFromFile(excelName);
        //设置转换后的PDF页面高宽适应工作表的内容大小
//        wb.getConverterSetting().setSheetFitToPage(true);
        //调用方法保存为PDF格式
        wb.saveToFile(pdfName, FileFormat.PDF);
    }

    public static void excelToPdf2(String excelName, String pdfName) {
        //加载Excel文档
        Workbook wb = new Workbook();
        wb.loadFromFile(excelName);
        String[] paths = new String[]{"font/OLDENGL.TTF",};

        wb.setCustomFontFilePaths(paths);

        CellRange range = wb.getWorksheets().get(0).getCellRange("A1");
        range.setText("self font");
        range.getStyle().getFont().setFontName("Old English Text MT");
        //设置转换后的PDF页面高宽适应工作表的内容大小
//        wb.getConverterSetting().setSheetFitToPage(true);
        //调用方法保存为PDF格式
        wb.saveToFile(pdfName);
    }

    /**
     * 根据打印机名称匹配打印机
     *
     * @param printerName 打印机名称
     * @return 打印驱动
     * @throws Exception 异常
     */
    public static PrinterJob findPrintService(String printerName) throws Exception {
        //获取打印驱动
        PrinterJob job = PrinterJob.getPrinterJob();
        // 遍历查询本地打印机名称
        for (PrintService service : PrinterJob.lookupPrintServices()) {
            String psName = service.toString();
            // 匹配对应的打印机
            if (psName.contains(printerName)) {
                job.setPrintService(service);
                return job;
            }
        }
        throw new RuntimeException("打印失败，未找到名称为" + printerName + "的打印机。");
    }

    /**
     * 设备打印属性
     *
     * @param document 要打印的文件
     * @param job      打印驱动
     */
    public static void configPageStyle(PDDocument document, PrinterJob job) {
        //设置纸张的大小和打印区域
        Paper paper = new Paper();
        paper.setSize(620, 840);
        paper.setImageableArea(10, 10, 620, 840);

        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        //设置页面打印方向
        pageFormat.setOrientation(PageFormat.PORTRAIT);

        Book book = new Book();
        book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, 1);
        //设置打印类
        job.setPageable(book);
    }

}
